package com.shi.yoyoshop.util;

import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

public class FileUtil {

    private static final String BASE_PATH = System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "webapp" + File.separator + "picture" + File.separator;

    public static String upload(MultipartFile file) throws IOException {
        String fileSuffix = fileSuffix(file.getOriginalFilename());
        if (ObjectUtils.isEmpty(fileSuffix)) {
            fileSuffix = "jpg";
        }
        String newFileName = UUID.randomUUID() + "." + fileSuffix;
        System.out.println("后缀：" + newFileName);
        try (InputStream inputStream = file.getInputStream();
             OutputStream outputStream = new FileOutputStream(BASE_PATH + newFileName);) {
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                outputStream.flush();
            }
        }
        return "picture" + File.separator + newFileName;
    }

    private static String fileSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static void main(String[] args) {
        System.out.println(fileSuffix("/a/b/cwad/test.txt"));
    }
}
